<template>
  <div class="bg-[#1a2c38] w-full min-375 h-auto" id="targetElement">
    <div class="container w-full mt-4">
      <!-- 通知栏 -->
      <ScrollingNotificationBar
        v-if="messageContent.length > 0"
        class="mb-4"
        :messageContent="messageContent"
      />
      <!-- 轮播图 -->
      <van-swipe
        class="mb-4"
        ref="carouselRef"
        indicator-color="white"
        v-show="isMobile"
      >
        <van-swipe-item
          ref="swiperheight"
          class="swiper_height"
          v-for="item in bannerList"
          :key="item"
          @click="clickGameOut(item)"
        >
          <div
            class="actvieBgc"
            :style="{
              backgroundImage: `url(${item.img_url})`
            }"
          ></div>
        </van-swipe-item>
      </van-swipe>

      <el-carousel
        ref="carouselRef"
        class="mb-4"
        :interval="1000"
        :autoplay="false"
        arrow="always"
        v-show="isPc"
      >
        <el-carousel-item
          ref="swiperheight"
          class="swiper_height"
          v-for="item in bannerList"
          :key="item"
          @click="clickGameOut(item)"
        >
          <img ref="imgheight" :src="item.img_url" style="width: 100%" alt="" />
        </el-carousel-item>
      </el-carousel>
      <Search class="mt-4" />

      <!-- 面包屑切换 -->
      <div class="mt-4 mb-4 overflow-x-auto">
        <div
          class="w-min flex space-x-4 p-2 overflow-y-hidden text-[#b1bad3] overflow-x-auto bg-[#0f212e] rounded-full"
        >
          <div
            v-for="(item, i) in tabs"
            @click="choseType(item.category_id, i, item.icon)"
            :key="i"
            class="flex items-center text-sm font-bold"
            :class="item.active ? 'active nav-item text-[#fff]' : 'nav-item'"
          >
            <img
              v-if="item.icon"
              :src="main.static_base_url + item.icon"
              class="menu-hover-img mr-[4px] max-w-none"
              :class="item.active ? 'menu-hover-img_hover' : ''"
              alt=""
            />
            <p>{{ item.name }}</p>
          </div>
        </div>
      </div>

      <!-- 供应商模块 -->
      <div class="text-[#fff]" v-if="showsupplier">
        <supplierData
          @updatadSupplier="changeShowsupplier"
          ref="supplierDatas"
        />
      </div>
      <!-- 默认大厅游戏 -->
      <div class="" v-if="!showAll" v-for="item in hallGames">
        <gameSwiper :details="item" v-if="route.path == '/casino'"></gameSwiper>
      </div>
      <!-- 特定分类游戏 -->
      <div v-else class="bg-[#1a2c38]">
        <div
          class="pt-4 flex items-center pl-4 pb-4 w-full bg-[#213743] group text-[#b1bad3] font-bold mt-4 text-lg"
        >
          <img
            v-if="tabsIcon"
            :src="main.static_base_url + tabsIcon"
            class="menu-hover-img menu-hover-img_hover mr-[4px]"
            alt=""
          />
          <span class="text-white">{{ tabsName }}</span>
        </div>
        <gameBox :games="games" />

        <p class="text-[#b1bad3] text-center">
          {{
            $t("page.casino.showtext1") +
            showtotal +
            $t("page.casino.showtext2") +
            games.length +
            $t("page.casino.showtext3")
          }}
        </p>
        <div
          v-if="showNextPage"
          @click="nextPage"
          class="w-[120px] m-auto mt-2 text-center bg-[#2f4553] text-white hover:bg-[#557086] px-4 py-2 rounded cursor-pointer"
        >
          {{ $t("page.casino.more") }}
        </div>
      </div>
      <more />
      <!-- <List /> -->
    </div>

    <!-- 弹窗 -->
    <!-- <activityPopup @getActiveDetil="getActiveDetil" /> -->
  </div>
</template>

<script setup name="Tools">
import {
  watch,
  createApp,
  ref,
  computed,
  onMounted,
  onActivated,
  onBeforeUnmount,
  nextTick,
  getCurrentInstance,
  defineAsyncComponent,
  onUnmounted
} from "vue";
const gameSwiper = defineAsyncComponent(() =>
  import("../../components/gameSwiper/index.vue")
);
import { NoticeBar } from "vant";
import ScrollingNotificationBar from "@/components/scrollingBotificationBar/index.vue";
const gameBox = defineAsyncComponent(() =>
  import("../../components/gameSwiper/gameBox.vue")
);
// const List = defineAsyncComponent(() => import("../../components/List/index.vue"));
// import gameSwiper from "../../components/gameSwiper/index.vue";
import {
  casionInit,
  gameList,
  gameSearch,
  typeIcon,
  gameCollect,
  gameCollectList
} from "../../api/casion.js";
import { init } from "../../api/user.js";
import { mainNav } from "@/store/nav";
import { mainAct } from "../../store/activeda";
// import { storeToRefs } from "pinia"; //引入pinia转换
const main = mainNav();
const main2 = mainAct();
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
import more from "@/components/more/index.vue";
import activityPopup from "@/components/activityPopup/index.vue";
import { mainWallet } from "@/store/wallet";
const Search = defineAsyncComponent(() =>
  import("@/components/search/index.vue")
);
const supplierData = defineAsyncComponent(() =>
  import("../../components/supplierData/index.vue")
);
import { eventBus } from "@/utils/eventBus.js";
const {
  appContext: {
    config: { globalProperties }
  }
} = getCurrentInstance();

import { gameDetail } from "@/store/game";

const gameDetails = gameDetail();

const mainWalletProp = mainWallet();
const games = ref([]);
const tabs = ref([]);
const hallGames = ref([]);
const tabsName = ref("");
const tabsIcon = ref(null);

const carouselRef = ref(null);
const showAll = ref(false);
const currentId = ref(null);
const currentPage = ref(1);
const showtotal = ref(null);
const showNextPage = ref(false);
//点击tabs
const nextPage = async () => {
  currentPage.value += 1;
  getGameListData();
};

const supplierDatas = ref(null);
const choseType = async (id, i, icon) => {
  valShowsupplier.value = [];
  games.value = [];

  currentPage.value = 1;
  tabsIcon.value = icon;
  // console.log(id,i);
  if (id == "all") {
    showAll.value = false;
    showsupplier.value = false;
    currentId.value = null;
    getCasionInit();
  } else {
    showsupplier.value = true;
    showAll.value = true;
    currentId.value = id;
    setTimeout(() => {
      supplierDatas.value?.clearElect();
    }, 100);
    getGameListData();
  }
};

const intervalId = ref(null);

const initialIndexImg = ref(0);
const isMobile = ref(false);
const isPc = ref(true);
import { isMobile as __isMobile } from "@/utils/isMobile";
window.onresize = () => {
  if (__isMobile()) {
    isMobile.value = true;
    isPc.value = false;
  } else {
    isMobile.value = false;
    isPc.value = true;
  }
};

onActivated(async () => {
  // nextTick(() => {
  //   console.log("娱乐城onactivted", localStorage.getItem("lang"));
  //   // getCasionInit();
  // });
  await getTypeIcon();
  await getCasionInit();
  eventBus.emit("changeActiveTab", "all");
});

onMounted(async () => {
  if (__isMobile()) {
    isMobile.value = true;
    isPc.value = false;
  } else {
    isMobile.value = false;
    isPc.value = true;
  }

  console.log("娱乐城onMounted", localStorage.getItem("lang"));
  intervalId.value = setInterval(() => {
    if (carouselRef.value) {
      carouselRef.value.next();
    }
  }, 4000);
  // carouselRef.value.autoplay = true;
  // let res = await init();
  // main2.static_base_url = res.data.static_base_url;
  // main2.currency = res.data.currency;
  // main2.lang_support_list = res.data.lang_support_list;
  // await getTypeIcon();
  // await getCasionInit();

  eventBus.on("reset", () => {
    choseType("all", 0, tabs.value[0].icon);
  });
  eventBus.off();

  if (main2.isLogin) {
    // await main2.getBalanceNumll();
    // getBa();
    // pollingId.value = setInterval(() => {
    //   getBa();
    // }, 10000);

    eventBus.emit("showActiveProp");
  }
});

const restTop = () => {};

onUnmounted(() => {
  clearInterval(intervalId.value);
});

const nextImg = () => {
  setInterval(() => {
    initialIndexImg.value++;
    console.log(
      "initialIndexImg.valueinitialIndexImg.value",
      initialIndexImg.value
    );
  }, 4000);
};

// eventBus.on("getActiveDetil", url => {
//   console.log("match", url);
//   clickGameOut(url);
// });

// login_game 游戏
// link 外部链接
// none 无跳转
// active 活动
// recharge 充值
// withdraw 提现

const getActiveDetil = data => {
  console.log("data", data);
  const substring = "login_game";

  let link_url = data.link_url;

  if (link_url.includes("login_game")) {
    if (!main2.isLogin) {
      if (main2._isMobile) {
        router.push("/login");
      } else {
        main2.showLoginLayer("no");
      }
      return;
    }
    const regex = /game_code=([^&]+)/;
    const match = link_url.match(regex);
    const gameCode = match[1]; // 提取捕获组中的值

    gameDetails.gameLogin(gameCode, router);
  } else if (link_url.includes("link")) {
    const regex = /url=([^&]+)/;
    const match = link_url.match(regex);
    const url = match[1]; // 提取捕获组中的值
    console.log("Game Code:", url);
    window.open(url);
  } else if (link_url.includes("active")) {
  } else if (link_url.includes("recharge")) {
    mainWalletProp.getBankInfo("showRecharge");
  } else {
    mainWalletProp.getBankInfo("showBank");
  }
};

import { strategyEntry } from "./data/index";

const clickGameOut = data => {
  const type = "";
  // stake://login_game? 正则 取出 login_game
  const match = data.link_url.match(/(?<=stake:\/\/)|(?<=jk:\/\/)[^?]+/)[0];
  console.log("match", data);

  strategyEntry(match, data.link_url);
};
const iconList = ref(null);
const getTypeIcon = async () => {
  let res = await typeIcon();
  if (res.errno == 0) {
    // console.log("⬇⬇   ---> icon分类 <---   ⬇⬇");
    let reg = /\\/g;
    res.data.list?.forEach(item => {
      item.icon = item.icon.replace(reg, "");
    });
    // console.log(res.data);
    iconList.value = res.data.list;
  }
};
const messageContent = ref("");
const bannerList = ref([]);

// getCasionInit 防抖
const debounce = (fn, delay) => {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
};

const getCasionInit = debounce(async () => {
  let data = {
    page_size: 20
  };
  tabs.value = [
    {
      name: globalProperties.$t("page.casino.all"),
      category_id: "all",
      active: true
    }
  ];
  let res = await casionInit(data);
  // console.log(res);
  // main.gameNav = res.data.category_nav;
  messageContent.value =
    res?.data?.hall_notice == null ? "" : res?.data.hall_notice?.content;
  res.data.category_lobby.forEach(items => {
    items.active = false;

    if (iconList.value && iconList.value.length) {
      iconList.value.forEach(iitem => {
        if (items.category_id == iitem.id) {
          items.icon = iitem.icon;
        }
      });
    }

    items.game_list.forEach(item => {
      if (!item.img_url.startsWith("http")) {
        item.img_url = main2.static_base_url + item.img_url;
      }
    });
  });

  tabs.value.push(...res.data.category_lobby);
  hallGames.value = res.data.category_lobby;
  bannerList.value = res.data.banner_list;
  bannerList.value.forEach(item => {
    item.img_url = main2.static_base_url + item.img_url;
  });
}, 1000);

const showsupplier = ref(false);
const valShowsupplier = ref([]);

const changeShowsupplier = val => {
  valShowsupplier.value = val;
  games.value = [];
  getGameListData();
};

eventBus.off();
eventBus.on("changeActiveTab", val => {
  if (val == "all") {
    choseType("all", 0, null);
  }
});

const getGameListData = () => {
  tabsName.value = "";

  let data = {
    category_id: currentId.value,
    page_size: 28,
    page: currentPage.value,
    business_code: valShowsupplier.value
  };
  gameList(data).then(res => {
    console.log(res);
    if (res.data.list) {
      showtotal.value = res.data.total;
      if (res.data.total > res.data.page * res.data.page_size) {
        showNextPage.value = true;
      } else {
        showNextPage.value = false;
      }
      res.data.list.forEach(item => {
        if (!item.img_url.startsWith("http")) {
          item.img_url = main2.static_base_url + item.img_url;
        }
      });
      games.value.push(...res.data.list);
    } else {
      games.value = [];
    }
    //修改状态 & 名字
    tabs.value.forEach(item => {
      if (item.category_id == currentId.value) {
        item.active = true;
        tabsName.value = item.name;
      } else {
        item.active = false;
      }
    });
    console.log("tabs.value/*/****", tabs.value);

    if (tabsName.value == "") {
      // 当中间没有找到对应的菜单name时，就找左侧的菜单
      let menuObj = main2.gameNav?.find(rows => rows.id == main.activeTab);
      tabsName.value = menuObj.name;
    }
  });
};

onMounted(() => {
  let url = window.location.href;
  console.log("url-----------------------", window.location, url);
  // 把这个 ? 后面的code的参数提取出来
  const regex = /code=([^&]+)/;
  const inivt_regex = /inviteCode=([^&]+)/;
  const match = url.match(regex);
  // const code = match?.[1]; // 提取捕获组中的值
  console.log("url.match(inivt_regex)", url.match(inivt_regex));
  let invit_code = "";
  if (url.includes("inviteCode")) {
    const urlObj = new URL(url);
    const params = new URLSearchParams(urlObj.search);
    invit_code = params.get("inviteCode");
  }
  let code = "";
  if (url.includes("code")) {
    const urlObj = new URL(url);
    const params = new URLSearchParams(urlObj.search);
    code = params.get("code");
  }

  // const invit_code = url.match(inivt_regex)?.[1];
  if (main.invit_code) {
    main.invit_code = main.invit_code;
  }
  if (!main.isLogin && code) {
    main.getGoogleCodeApi({ code: decodeURIComponent(code) });
    main.closeLoginLayer();
    window.history.replaceState({}, document.title, url.split("?")[0]);
  }
});
</script>
<style scoped lang="less">
.my-swipe {
  width: 80vw;
  margin: auto;
  margin-bottom: 2rem;
  // .van-swipe-item {
  //   color: #fff;
  //   font-size: 20px;
  //   line-height: 150px;
  //   text-align: center;
  //   img {
  //     width: 80vw;
  //     max-width: 1200px;
  //     min-width: 500px;
  //   }
  // }
}

// .el-carousel__item h3 {
//   color: #475669;
//   opacity: 0.75;
//   line-height: 300px;
//   margin: 0;
//   text-align: center;
// }

.el-carousel__item:nth-child(2n) {
  // background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  // background-color: #d3dce6;
}

::v-deep(.el-carousel__indicators) {
  // display: none;
}

.el-carousel__indicators,
.el-carousel__indicator--horizontal {
  // display: none;
}
.greenpoint {
  animation: svelte-tgp09d-pulse 1s infinite ease-out;
}
@keyframes svelte-tgp09d-pulse {
  0% {
    box-shadow: 0 0 #00e70166;
  }
  30% {
    box-shadow: 0 0 2px 2px #00e70166;
  }
  70% {
    box-shadow: 0 0 2px 2px #00e70166;
  }
  100% {
    box-shadow: 0 0 #00e70166;
  }
}
.nav-item {
  // color: #b1bad3;
  padding: 10px 20px;
  cursor: pointer;
  white-space: nowrap;
}

.nav-item:hover {
  background-color: #2f4553;
  border-radius: 20px;
}

.nav-item.active {
  background-color: #2f4553;
  border-radius: 20px;
}

.container {
  overflow: hidden;
}

.swiper_height {
  height: 290px;
}

@media screen and (min-width: 600px) and (max-width: 800px) {
  .swiper_height {
    height: 170px !important;
  }
  ::v-deep(.el-carousel__container) {
    height: 170px;
  }
}
@media screen and (min-width: 800px) and (max-width: 1000px) {
  .swiper_height {
    height: 220px !important;
  }
  ::v-deep(.el-carousel__container) {
    height: 220px;
  }
}
@media screen and (min-width: 1000px) and (max-width: 1200px) {
  .swiper_height {
    height: 230px !important;
  }
  ::v-deep(.el-carousel__container) {
    height: 230px;
  }
}
@media screen and (min-width: 1200px) and (max-width: 1400px) {
  .swiper_height {
    height: 290px !important;
  }
  ::v-deep(.el-carousel__container) {
    height: 290px;
  }
}
@media (max-width: 600px) {
  .swiper_height {
    height: 150px !important;
  }

  ::v-deep(.el-carousel__container) {
    height: 150px;
  }

  .game-card {
    width: 30% !important;
    max-width: unset;
  }

  .banner {
    height: 80px !important;
    line-height: 80px !important;
  }

  .gameBox {
    grid-gap: 10px 5px !important;
    grid-template-columns: repeat(3, 1fr) !important;

    .item {
      width: 28vw !important;
      max-width: unset;
      min-width: unset;
    }
    .game_loading_div {
      width: 28vw !important;
      height: 36vw !important;
    }
    .star {
      display: block !important;
    }
    .mb {
      opacity: 1 !important;
    }
  }
}

.game-card:hover {
  transform: translateY(-4%);
}

.game-card {
  max-width: 200px;
  width: 200px;
  height: 250px;
  cursor: pointer;
  background-color: #667386;
  border-radius: 10px;
  /* padding: 20px; */
  text-align: center;
  margin: 10px;
  /* flex: 1 0 21%; Adjust the flex-basis to control the number of items per row */
  position: relative;
  will-change: transform;
  transition: 0.3s;

  .game-card-con {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;

    img {
      width: auto;
      min-width: 200px;
      border-radius: 10px;
    }

    p {
      margin-top: 10px;
      color: #ffffff;
    }

    .players {
      color: #00ff00;
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.pagination button {
  background-color: #1c2a38;
  color: #ffffff;
  border: none;
  padding: 10px 20px;
  padding-top: 15px;
  margin: 0 5px;
  cursor: pointer;
  border-radius: 5px;
  border: 1px solid #2f4453;
}

.pagination button:first-child {
  margin-right: 0;
  border-radius: 40% 0 0 40%;
  border-right: 0;
}

.pagination button:last-child {
  margin-left: 0;
  border-radius: 0 40% 40% 0;
}

.pagination button.disabled {
  background-color: #1a2c38;
  color: #667386;
  cursor: not-allowed;
}

.banner {
  color: #fff;
  font-weight: 600;
  font-size: 20px;
  height: 115px;
  line-height: 115px;
}

.menu-hover-img {
  width: 20px;
}

.menu-hover-img:hover {
  filter: brightness(200%); /* 增加亮度来实现高亮效果 */
  transition: filter 0.1s ease; /* 平滑过渡效果 */
}

.menu-hover-img_hover {
  filter: brightness(200%); /* 增加亮度来实现高亮效果 */
  transition: filter 0.1s ease; /* 平滑过渡效果 */
}

.gameBox {
  background-color: #1a2c38;
  display: grid;
  grid-gap: 2rem 1rem;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  .hover-img {
    will-change: transform;
    transition: 0.3s;
  }
  .item .game_loading_div {
    width: 157px;
    color: #fff;
    height: 216px;
    cursor: pointer;
    background-color: #213743;
    text-align: center;
    line-height: 216px;
    border-radius: 4px;
  }
  .star {
    display: none;
  }
  .mb {
    opacity: 0;
    transition-duration: 1s;
    transition-property: opacity;
    background: linear-gradient(
      0deg,
      rgba(255, 255, 255, 0) 0%,
      rgba(0, 0, 0, 0.3) 25%,
      rgba(0, 0, 0, 0.5) 60%,
      rgba(48, 48, 48, 0.9) 100%
    );
  }

  .item:hover .hover-img {
    transform: translateY(-4%);
    .star {
      display: block;
      z-index: 12;
    }
    .mb {
      opacity: 1;
      transition-duration: 1s;
      transition-property: opacity;
      z-index: 11;
    }
  }
}
:deep(.el-select__wrapper) {
  background: #0f212e;
}
.actvieBgc {
  width: 100%;
  height: 100%;
  background-size: cover; /* 覆盖整个元素区域 */
  background-repeat: no-repeat; /* 不重复图片 */
  background-position: center; /* 居中显示 */
}
</style>
